//
//  PickerValueCell.m
//  iShop
//
//  Created by svp on 20/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "TitleTextfieldCell.h"

#define DisplayMember 0
#define ValueMember 1

@implementation TitleTextfieldCell

@synthesize textField = _textField;
@synthesize titleLabel = _titleLabel;
@synthesize delegate = _delegate;

-(BOOL) initPickerWithArray:(NSArray*) array
{
	if (!_pickerArray) {
		_pickerArray = [array copy];
		_pickerView = [[UIPickerView alloc] init];
		_pickerView.dataSource = self;
		_pickerView.showsSelectionIndicator = YES;
		_textField.inputView = _pickerView;
		_pickerView.delegate = self;
	}
	else
	{
		[_pickerArray release];
		_pickerArray = nil;
		_pickerArray = [array copy];
		[_pickerView reloadAllComponents];
	}	
	[_pickerView reloadAllComponents];
	[_pickerView selectRow:0 inComponent:0 animated:YES];
	_textField.text = [[_pickerArray objectAtIndex:0] objectAtIndex:DisplayMember];
	return YES;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return _pickerArray.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	return [[_pickerArray objectAtIndex:row] objectAtIndex:DisplayMember];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	_selectedIndex = row;
	_textField.text = [[_pickerArray objectAtIndex:row] objectAtIndex:DisplayMember];
	if (_delegate && [_delegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
		[_delegate textFieldDidEndEditing:self];
	}
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
	if (_delegate && [_delegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) {
		[_delegate textFieldDidBeginEditing:self];
	}
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
	if (_delegate && [_delegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
		[_delegate textFieldDidEndEditing:self];
	}
}

-(void) layoutSubviews
{
	[super layoutSubviews];
	//DO STUFF
}

-(void) dealloc
{
	NSLog(@"Error here");
	[_textField release];
	[_titleLabel release];
	[super dealloc];
}

-(NSString*) cellValue
{
	if (_pickerArray != nil && _pickerArray.count > 0) {
		for (NSArray *arr in _pickerArray) {
			if ([[arr objectAtIndex:DisplayMember] isEqualToString:_textField.text]) {
				return [arr objectAtIndex:ValueMember];
			}
		}		
	}
	else {
		return _textField.text;
	}

	return nil;
}

-(void) setPickerSelectAt:(NSString*)value
{
	for (int i= 0;i<_pickerArray.count;i++) {
		if ([[[_pickerArray objectAtIndex:i] objectAtIndex:ValueMember] isEqualToString:value]) {
			[_pickerView reloadAllComponents];
			[_pickerView selectRow:i inComponent:0 animated:YES];
			_textField.text = [[_pickerArray objectAtIndex:i] objectAtIndex:DisplayMember];
			break;
		}
	}
}

@end
